<template>
  <!-- <div>{{this.$route.query.iid}}</div> -->
  <div id="detail">
    <detail-navbar
      class="detail-nav"
      @navbarClick="navbarClick"
      ref="detailNavbar"
    ></detail-navbar>
    <scroll
      class="content"
      ref="scroll"
      probeType="3"
      @scrollPosition="scrollPosition"
    >
      <div>
        <detail-swaper :topImages="topImages" ref="swaper"></detail-swaper>
        <detail-base :goods="goods"></detail-base>
        <detail-shop-info :shop="shop"></detail-shop-info>
        <detail-goods-info
          :detailInfo="detailInfo"
          @imgLoad="imgLoad"
        ></detail-goods-info>
        <detail-param :paramInfo="paramInfo" ref="paramInfo"></detail-param>
        <detail-comment-info
          :commentInfo="commentInfo"
          ref="commentInfo"
        ></detail-comment-info>
        <detail-recommend-info
          :recommendList="recommendList"
          ref="recommendInfo"
        ></detail-recommend-info>
      </div>
    </scroll>
    <detail-bottom-bar @addToCart="addToCart"></detail-bottom-bar>
    <backtop @click.native="backTopClick()" v-show="isShowBackTop"></backtop>

  </div>
</template> 

<script>
import DetailNavbar from "./childComps/DetailNavbar.vue";
import {
  getGoodsDetail,
  Goods,
  Shop,
  GoodsParam,
  getRecommend
} from "network/goodsdetail";
import DetailSwaper from "./childComps/DetailSwaper.vue";
import DetailBase from "./childComps/DetailBase.vue";
import DetailShopInfo from "./childComps/DetailShopInfo.vue";
import Scroll from "../../components/common/scroll/Scroll.vue";
import DetailGoodsInfo from "./childComps/DetailGoodsInfo.vue";
import DetailParam from "./childComps/DetailParam.vue";
import DetailCommentInfo from "./childComps/DetailCommentInfo.vue";
import DetailRecommendInfo from "./childComps/DetailRecommendInfo.vue";
import DetailBottomBar from "./childComps/DetailBottomBar.vue";
import Backtop from "../../components/content/backtop/Backtop.vue";
import { BacktopMixin } from "@/common/mixin.js";
import { mapActions } from "vuex";

export default {
  name: "GoodsDetail",
  components: {
    DetailNavbar,
    DetailSwaper,
    DetailBase,
    DetailShopInfo,
    Scroll,
    DetailGoodsInfo,
    DetailParam,
    DetailCommentInfo,
    DetailRecommendInfo,
    DetailBottomBar,
    Backtop,
  },
  mixins: [BacktopMixin],
  data() {
    return {
      iid: null,
      // 轮播图片数据信息
      topImages: [],
      goods: {},
      shop: {},
      detailInfo: {},
      // 商品详情页 参数页信息
      paramInfo: {},
      commentInfo: {},
      recommendList: [],
      itemImgListener: null,
      // 每个组件对应的offsettop
      componentsOffSetTop: []
    };
  },
  created() {
    this.iid = this.$route.query.iid;
    // 根据iid请求数据
    getGoodsDetail(this.iid).then(res => {
      console.log("goods data", res);
      // 获取轮播图数据
      this.topImages = res.result.itemInfo.topImages;
      // console.log(this.topImage);
      // 获取商品信息
      this.goods = new Goods(
        res.result.itemInfo,
        res.result.columns,
        res.result.shopInfo
      );
      // console.log(this.goods);
      // 获取商家信息
      this.shop = new Shop(res.result.shopInfo);

      //获取商品更多详情信息
      this.detailInfo = res.result.detailInfo;

      //  商品详情页参数数据
      this.paramInfo = new GoodsParam(
        res.result.itemParams.info,
        res.result.itemParams.rule
      );

      // 评论信息数据
      // != 比较时，若类型不同，会偿试转换类型。!== 只有相同类型才会比较。
      if (res.result.rate) {
        this.commentInfo = res.result.rate.list[0];
      }
    });
    getRecommend().then(res => {
      console.log("recommend data", res);
      this.recommendList = res.data.list;
    });
  },

  // 监听goodlist组件的图片加载并且refresh
  mounted() {
    // 对监听的函数做个保存
    this.itemImgListener = () => {
      // console.log("home监听到图片加载成功了");
      // 每次监听到一张图片加载完成之后就刷新betterscroll 会影响性能
      this.$refs.scroll && this.$refs.scroll.refresh();
    };

    this.$bus.$on("itemload", this.itemImgListener);
  },
  methods: {
    // 监听detail-goods-info组件的图片加载
    imgLoad() {
      // console.log("刷新前", this.$refs.scroll.$el.scrollHeight);
      this.$refs.scroll.refresh();
      // console.log("刷新后", this.$refs.scroll.$el.scrollHeight);
      // console.log("监听到detailGoodsinfo发送的事件了");
      console.log("goods-info加载后获得的offsettop值");

      //图片加载完成后，开始计算每个组件对应的offsettop值 为scrollPosition监听方法做准备
      this.getItemOffSetTop();
    },
    // 监听navbar点击 并且跳转到对应的y值
    navbarClick(index) {
      this.getItemOffSetTop();
      this.$refs.scroll.scrollTo(0, -this.componentsOffSetTop[index], 0);
    },

    //计算每个组件的offsettop
    getItemOffSetTop() {
      this.componentsOffSetTop = [];
      // 商品标签的offsettop永远是
      this.componentsOffSetTop.push(0);
      this.componentsOffSetTop.push(this.$refs.paramInfo.$el.offsetTop);
      this.componentsOffSetTop.push(this.$refs.commentInfo.$el.offsetTop);
      this.componentsOffSetTop.push(this.$refs.recommendInfo.$el.offsetTop);
      console.log('offsettop的值是',this.componentsOffSetTop);
    },

    //  监听scroll组件的滚动位置 并且让navbar同时高亮显示对应的项目
    scrollPosition(position) {
      // 当前的position和componentsOffSetTop里面的y值作比较 并且把数组的index值传给detail-nav-bar的currentIndex

      //  position 在 componentsOffSetTop[0] 和 [1]时候 赋值0给currentindex
      //  position 在 componentsOffSetTop[1] 和 [2]时候 赋值1
      //  position 在 componentsOffSetTop[2] 和 [3]时候 赋值2

      /*  //  自己写的算法  有点垃圾
      if (
        -position.y > this.componentsOffSetTop[0] &&
        -position.y < this.componentsOffSetTop[1] &&
        this.$refs.detailNavbar.currentIndex != 0
      )
        this.$refs.detailNavbar.currentIndex = 0;

      if (
        -position.y > this.componentsOffSetTop[1] &&
        -position.y < this.componentsOffSetTop[2] &&
        this.$refs.detailNavbar.currentIndex != 1
      )
        this.$refs.detailNavbar.currentIndex = 1;


      if (
        -position.y > this.componentsOffSetTop[2] &&
        -position.y < this.componentsOffSetTop[3] &&
        this.$refs.detailNavbar.currentIndex != 2
      )
        this.$refs.detailNavbar.currentIndex = 2;

      if (
        -position.y > this.componentsOffSetTop[3] &&
        this.$refs.detailNavbar.currentIndex != 3
      )
        this.$refs.detailNavbar.currentIndex = 3; */

      // codewhy的算法 自己写挺简单的
      for (let i in this.componentsOffSetTop) {
        // 上面这个遍历出来的i是个string类型的值
        const realI = parseInt(i);
        if (
          // 当不是当前项目的时候 才有必要进行比较
          this.$refs.detailNavbar.currentIndex != realI &&
          // 当realI不是最后一项的时候
          ((realI < this.componentsOffSetTop.length - 1 &&
            -position.y > this.componentsOffSetTop[realI] &&
            -position.y < this.componentsOffSetTop[realI + 1]) ||
            // 当realI是最后一项的时候
            (realI == this.componentsOffSetTop.length - 1 &&
              -position.y > this.componentsOffSetTop[realI]))
        ) {
          this.$refs.detailNavbar.currentIndex = realI;
          console.log(realI);
        }

        this.isShowBackTop = position.y < -750;
      }
    },
    // mapaction引入vuex中的action 变成methods
    ...mapActions(["addCart"]),
    addToCart() {
      // 1.创建商品对象 后续push到vuex中的对象数组中
      const obj = {};
      // 2.对象信息
      obj.iid = this.iid;
      obj.imgURL = this.topImages[0];
      obj.title = this.goods.title;
      obj.desc = this.goods.desc;
      obj.newPrice = this.goods.realPrice;
      // 3.添加到Vuex Store中
      // this.$store.dispatch("addCart", obj);

     
      // 调用mapaction转换的方法监听添加购物车操作返回的结果
      this.addCart(obj).then(res => this.$toast2(res,1000));
    }
  },
  // 没有Keepalive的组件会被直接销毁 而不是deactived
  destroyed() {
    this.$bus.$off("itemload", this.itemImgListener);
    // console.log(this.$bus.$off+'事件总线取消了');
  }
};
</script>

<style>
#detail {
  position: relative;
  z-index: 9;
  background-color: #fff;
  height: 100vh;
}
.detail-nav {
  position: relative;
  z-index: 9;
  background-color: #fff;
}
.content {
  /* 100%是相对父元素 #detail */
  height: calc(100% - 102px);
  position: relative;
  top: 0px;
  /* bottom: 58px; */
}
</style>
